package org.example.springbootexperiment03.dao;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.example.springbootexperiment03.config.RegionPropertiesConfig;
import org.example.springbootexperiment03.pojo.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.*;

/**
 * Created by bothin
 * At 2020/5/7 14:18
 * Description:
 */
@Repository
public class RegionDao {
    /**
     * 保存数据
     */
    private List<Region> dataList = new ArrayList<>();

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RegionPropertiesConfig regionProperties;

    public List<Region> getALLRegions(){
        return dataList;
    }

    /**
     * 从url上爬取数据
     * @throws IOException
     */
    public void pullData() throws IOException {
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(regionProperties.getUrl()))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> responseEntity = restTemplate.exchange(requestEntity, Resource.class);
        Resource resource = responseEntity.getBody();

        Reader in = new InputStreamReader(resource.getInputStream(), "UTF-8");
        Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
        //Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
        boolean isHeader = true;
        List<String> datelist = new ArrayList<>();  //获取表头（每天的日期）
        int id = 0;
        for (CSVRecord record : records) {
            //获取表头
            if (isHeader) {
                isHeader = false;
                //从第5列开始是日期/病例
                for (int i = record.size() - 1; i >= 4; i--) {
                    String[] split = record.get(i).split("/");
                    datelist.add("20"+split[2]+"年"+split[0]+"月"+split[1]+"日");
                }
            } else {
                //获取数据
                Region region = new Region();
                Map<String,Long> map = new LinkedHashMap<>();
                //从第5列开始是日期/病例
                for (int i = record.size() - 1, j = 0; i >= 4; i--, j++) {
                    map.put(datelist.get(j), Long.valueOf(record.get(i)));
                }
                region.setData(map);
                region.setId(id++);
                region.setProvinceName(record.get(0));
                region.setCountryName(record.get(1));
                dataList.add(region);
            }
        }
    }


}
